# -*- coding: utf-8 -*-
"""
/***************************************************************************
 pca
                                 A QGIS plugin
 Principal Component Analysis for rasters
                             -------------------
        begin                : 2013-04-29
        copyright            : (C) 2013, 2014 by Stavros Georgousis
        email                : grgeosteve@gmail.com
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 3 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""

import csv
from osgeo import gdal
from osgeo.gdalconst import *
import numpy

def Raster2asciiAlg(inputRasterFileName, outputCSVFileName, LabelBandNo=1):
    # Open the input raster file
    # register the gdal drivers
    gdal.AllRegister()

    # Open and assign the contents of the raster file to a dataset
    dataset = gdal.Open(inputRasterFileName, GA_ReadOnly)
    csvfile = file(outputCSVFileName, 'wb')
    writer = csv.writer(csvfile)
     
    oldArray = dataset.ReadAsArray(0, 0, 
                                   dataset.RasterXSize, 
                                   dataset.RasterYSize).astype(numpy.float64)
    datas = [ i for i in oldArray ]
    datas = [ numpy.reshape(i,(-1,1) ) for i in oldArray ]
    datas = numpy.concatenate(datas,1)
    
    for dataLine in datas:
        if LabelBandNo == 1:
            writer.writerow(dataLine)
        else:
            dataLine[0],dataLine[LabelBandNo-1] = dataLine[LabelBandNo-1], dataLine[0]
            writer.writerow(dataLine)

    csvfile.close()
    dataset = None
 
#if __name__ == "__main__":
#    inputRasterFileName = r"h:\RSIA_SVM\result\Label_Features.tif"
#    outputCSVFileName=r"h:\RSIA_SVM\result\Label_Features2.csv"
#    Raster2asciiAlg(inputRasterFileName, outputCSVFileName, 4)